import { defineComponent, onMounted, PropType, ref, watch, getCurrentInstance} from 'vue';
/* utils */
import dayjs from 'dayjs';
import { t } from '@src/locales'
import { message } from '@src/util/message'
import { postPage } from 'pub-bbx-utils'
/* enum */
import { ConnectorModuleComponentNameEnum } from '@src/modules/connector/model/enum.ts';
/* scss */
import '@src/modules/connector/view/list/components/table/index.scss';
import { TriggerSettingCardItem } from '@src/modules/connector';
/* api */
import * as TriggerApi from '@src/modules/connector/api/trigger';
import NoDataViewNew from '@src/component/common/NoDataViewNew';
/* components */
import { Notification, Button } from 'element-ui'


export enum ConnectorListViewCardItemEmitEventNameEnum {
  Input = 'input',
  Update = 'update',
  Edit = 'edit',
  Delete = 'delete',
  UpdateState = 'updateState',
  Log = 'log'
}

export default defineComponent({
  name: ConnectorModuleComponentNameEnum.ConnectorListViewTable,
  props: {
    value: {
      type: Array as PropType<TriggerSettingCardItem[]>,
      default: () => [],
    },
    loading:{
      type:Boolean,
      default: true
    },
    edit: {
      type: Boolean,
      default: false,
    },
    delete: {
      type: Boolean,
      default: false,
    }
  },
  setup(props) {
    const instance = getCurrentInstance();
    let pageSize = ref(30);
    let pageNum = ref(1);
    let total = ref(props.value.length);
    let tableData = ref([] as any);
    const defaultTableData = {
      defaultPageSizes: [10, 20, 30, 40, 50, 100],
    };
    /**
     * @description 获取分页数据
     */
    const getPaginatedData = () => {
      const start = (pageNum.value - 1) * pageSize.value;
      const end = pageNum.value * pageSize.value;
      tableData.value = props.value.slice(start, end);
    };

    const dosageNotification = ({used= 0, total= 0}) => {
      const h = instance?.proxy.$createElement
			Notification({
				customClass: 'isEnable-notification',
				type: 'info',
				title: t("trigger.tip.text1"),
				duration: 0,
				message: h('div', [
					h('p', { style: { marginTop: '16px' } }, `${t("trigger.tip.text2")} ${used}/${total}`),
					h('p', { style: { marginBottom: '16px' } }, t("trigger.tip.text3")),
					h(Button, {
						props: { type: 'primary' },
            on: { click: jumpContactUs }
					}, t("trigger.tip.text4"))
				]),
			});
		}

		const jumpContactUs = () => {
			postPage({
        action: 'shb.system.openChat',
        data: {}
      })
    }
    /**
     * @description 启用用户处理函数
     * @param val 
     * @param row 
     */
    const handleSwitchChange = (val: number, row) => {
      if (!props.edit) {
        return
      }
      TriggerApi.updateTriggerStat({ triggerId: row.id, enable: val }).then((res: any) => {
        if (res.status == 0) {
          const item = tableData.value.find(item => item.id === row.id);
          if (item) {
            item.enable = val;
            if (val === 0) {
              message.success(t('trigger.button.disableSuccess'))
            } else {
              message.success(t('trigger.button.enableSuccess'))
            }
          }
        } else if (res.stauts === 20001){
          dosageNotification({used: res.data.used, total: res.data.total})
        } else {
          message.error(res.message);
        }
      });
    };

    /**
     * @description 初始化分页参数
     */
    const initTableparams = () => {
      pageSize.value = 30;
      pageNum.value = 1;
      total.value = props.value.length;
    }

    watch(() => pageSize.value, () => getPaginatedData())
    watch(() => pageNum.value, () => getPaginatedData())

    watch(() => props.value, () => {
      initTableparams();
      getPaginatedData()
    }, { immediate: true })

    return {
      pageSize,
      pageNum,
      total,
      tableData,
      defaultTableData,
      getPaginatedData,
      handleSwitchChange,
    };
  },
  methods: {
    /**
     * @description 渲染操作列
     */
    renderAction(row: any) {
      return (
        <div class={'connector-list-view-table-action'}>
          <el-button type={'text'} onClick={() => this.$emit(ConnectorListViewCardItemEmitEventNameEnum.Edit, row)} v-show={this.edit}>{t("common.base.edit")}</el-button>
          <el-button type={'text'}  onClick={() => this.$emit(ConnectorListViewCardItemEmitEventNameEnum.Log, row)}>{t('common.pageTitle.pageCallLog2')}</el-button>
          <el-button type={'text'}  onClick={() => this.$emit(ConnectorListViewCardItemEmitEventNameEnum.Delete, row)} v-show={this.delete}>{t('common.base.delete')}</el-button>

          {/* <el-dropdown placement="bottom">
            
            <span class={'connector-list-view-table-action-more'}>{t("common.base.more")}<i class="iconfont down">&#xe785;</i></span>
            
            <el-dropdown-menu slot="dropdown">
              
              <el-dropdown-item v-show={this.edit}>
                <div onClick={() => this.$emit(ConnectorListViewCardItemEmitEventNameEnum.Update, row)} >
                  {t('common.base.rename')}
                </div>
              </el-dropdown-item>
              
              <el-dropdown-item v-show={this.delete}>
                <div onClick={() => this.$emit(ConnectorListViewCardItemEmitEventNameEnum.Delete, row)}>
                  {t('common.base.delete')}
                </div>
              </el-dropdown-item>

              <el-dropdown-item>
                <div onClick={() => this.$emit(ConnectorListViewCardItemEmitEventNameEnum.Log, row)}>
                  {t('common.pageTitle.pageCallLog')}
                </div>
              </el-dropdown-item>
              
            </el-dropdown-menu>
            
          </el-dropdown> */}
        </div>
      );
    },
    /**
     * @description 页面回到顶部事件
     */
    pageTo() {
      const table = document.querySelector(".connector-list-view-table .table .el-table__body-wrapper") || window
      table.scrollTop = 0;
    },
    currentChangeHandler(val) {
      this.pageNum = val
      this.pageTo()
    },
    sizeChangeHandler(val) {
      this.pageSize = val
      this.pageTo()
    }
  },
  render() {
    const directives = [{name: 'loading', value: this.loading}]
    return (
      <div class={ConnectorModuleComponentNameEnum.ConnectorListViewTable} {...{directives}}>
        <div class="table">
          <el-table data={this.tableData} border={true} min-width={'100%'} height={'100%'}
          rowStyle={{ height: '64px' }}
          headerCellStyle={{ background: '#fafafa', color: '#262626' }}
          scopedSlots={{
            empty: ({ row }) => {
              return (
                <NoDataViewNew />
              )
            }
          }}
        >
          <el-table-column
            label={t("trigger.table.tName")}
            min-width={'240px'}
            scopedSlots={{
              default: ({ row }) => {
                return (
                  <div class={'connector-list-view-table-name'}>
                    <div class={'name-text'}>{row.triggerName || '-'}</div>
                    <div class={'name-text-tips'}><span>{row.triggerDesc || ''}</span></div>
                  </div>
                );
              },
            }}
          />
          <el-table-column label={t("trigger.table.tId")} prop={'triggerNo'} min-width={'150px'}/>
          <el-table-column
            label={t("trigger.table.updatePerson")}
            min-width={'120px'}
            scopedSlots={{
              default: ({ row }) => {
                const updateUserName = row.updateUser?.name || '-';
                return <div class={'connector-list-view-table-name'}>{updateUserName}</div>;
              },
            }}
          />
          <el-table-column
            label={t("trigger.table.updateTime")}
            min-width={'160px'}
            scopedSlots={{
              default: ({ row }) => {
                let updateTime = row.updateTime;
                updateTime ? (updateTime = dayjs(updateTime).format('YYYY-MM-DD HH:mm:ss')) : '';
                return <div class={'connector-list-view-table-name'}>{updateTime}</div>;
              },
            }}
          />
          <el-table-column
            label={t("trigger.table.createPerson")}
            min-width={'120px'}
            scopedSlots={{
              default: ({ row }) => {
                const createUser = row.createUser.name || '-';
                return <div class={'connector-list-view-table-name'}>{createUser}</div>;
              },
            }}
          />
          <el-table-column
            label={t("trigger.table.createTime")}
            min-width={'160px'}
            scopedSlots={{
              default: ({ row }) => {
                let createTime = row.createTime;
                createTime ? (createTime = dayjs(createTime).format('YYYY-MM-DD HH:mm:ss')) : ''
                return <div class={'connector-list-view-table-name'}>{createTime}</div>;
              },
            }}
          />
          <el-table-column
            label={t("trigger.table.enable")}
            min-width={'120px'}
            scopedSlots={{
              default: ({ row }) => {
                const onSwitchChange = val => this.handleSwitchChange(val, row);
                return (
                  <div class={'connector-list-view-table-name'}>
                    
                    {
                      this.edit ? (
                        <el-switch active-value={1}  inactive-value={0} key={row.id}  value={row.enable}  disabled={!this.edit} onChange={onSwitchChange} />
                      ) : (
                        <el-tooltip class="item" effect="dark" key={row.id} content={t('trigger.isAuth')}  placement="top-start">
                          <el-switch
                             disabled={this.edit}
                             active-value={1}
                             inactive-value={0}
                             key={row.id}
                             value={row.enable}
                             onChange={onSwitchChange}
                           >
                          </el-switch>
                        </el-tooltip>
                      )
                    }
                  </div>
                );
              },
            }}
          />
          <el-table-column
            label={t("trigger.table.action")}
            fixed={'right'}
            width={'200px'}
            scopedSlots={{
              default: ({ row }) => {
                return this.renderAction(row);
              },
            }}
          />
          </el-table>
        </div>
        <div class={'connector-list-view-table-pagination'}>
          <div class="connector-list-view-table-pagination-total">
          {t("trigger.table.g")}&nbsp;<span>{this.total}</span>&nbsp;{t("trigger.table.t")}
          </div>
          <el-pagination 
            class="table-pagination" 
            background currentPage={this.pageNum} 
            pageSize={this.pageSize} 
            pageSizes={this.defaultTableData.defaultPageSizes} 
            layout={'prev, pager, next, sizes, jumper'} 
            total={this.total}
            onCurrent-change={(val) => this.currentChangeHandler(val)}
            onSize-change={(val) => this.sizeChangeHandler(val)}
          >
          </el-pagination>
        </div>
      </div>
    );
  },
});
